package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.config.CrmebConfig;
import com.zbkj.common.constants.RegularConstants;
import com.zbkj.common.constants.SmsConstants;
import com.zbkj.common.enums.RoleEnum;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.admin.SystemRole;
import com.zbkj.common.model.client.agent.*;
import com.zbkj.common.request.*;
import com.zbkj.common.response.SystemAdminResponse;
import com.zbkj.common.result.AdminResultCode;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.service.dao.SystemAdminDao;
import com.zbkj.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * SystemAdminServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@Service
public class SystemAdminServiceImpl extends ServiceImpl<SystemAdminDao, SystemAdmin> implements SystemAdminService {

    @Resource
    private SystemAdminDao dao;

    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private CrmebConfig crmebConfig;

    @Autowired
    private UserLocationService userLocationService;

    @Autowired
    private WeekTaskService weekTaskService;

    @Autowired
    private SpecialHotTopicServiceImpl specialHotTopicService;

    @Autowired
    private UserSpecialTopicCategoryService userSpecialTopicCategoryService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${workbench.agent}")
    private String agentBaseUrl;


    /**
     * 通过用户名获取用户
     *
     * @param username 用户名
     * @param type     用户类型
     * @return SystemAdmin
     */
    @Override
    public SystemAdmin selectUserByUserNameAndType(String username, Integer type) {
        List<Integer> types = addSuperRoleType(type);
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getAccount, username);
        lqw.in(SystemAdmin::getType, types);
        lqw.eq(SystemAdmin::getIsDel, false);
        lqw.last(" limit 1");
        return dao.selectOne(lqw);
    }

    /**
     * 通过手机号获取用户
     *
     * @param phone 手机号
     * @return SystemAdmin
     */
    @Override
    public SystemAdmin selectUserByPhone(String phone) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getPhone, phone);
        lqw.eq(SystemAdmin::getIsDel, false);
        lqw.last(" limit 1");
        return dao.selectOne(lqw);
    }

    /**
     * 后台管理员列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return List
     */
    @Override
    public List<SystemAdminResponse> getList(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带SystemAdminRequest类的多条件查询
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotNull(request.getStatus())) {
            lqw.eq(SystemAdmin::getStatus, request.getStatus());
        }
        if (StrUtil.isNotBlank(request.getRealName())) {
            String decode = URLUtil.decode(request.getRealName());
            lqw.and(i -> i.like(SystemAdmin::getRealName, decode)
                    .or().like(SystemAdmin::getAccount, decode));
        }
        SystemAdmin currentAdmin = SecurityUtil.getLoginUserVo().getUser();
        lqw.eq(SystemAdmin::getMerId, currentAdmin.getMerId());
        // 超级管理员查看平台账户 商户超级管理员查看自己和商户管理员
        // 1=1，2,3 2=2，4
        List<Integer> types = new ArrayList<>();
        if (currentAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            types.add(RoleEnum.MERCHANT_ADMIN.getValue());
            types.add(RoleEnum.SUPER_MERCHANT.getValue());
            lqw.in(SystemAdmin::getType, types);
        } else if (currentAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())) {
            types.add(RoleEnum.PLATFORM_ADMIN.getValue());
            types.add(RoleEnum.SUPER_ADMIN.getValue());
            lqw.in(SystemAdmin::getType, types);
        } else {
            lqw.eq(SystemAdmin::getType, systemRoleService.getRoleTypeByCurrentAdmin());
        }
        if (ObjectUtil.isNotNull(request.getRoles()) && request.getRoles() > 0) {
            lqw.apply(" find_in_set({0}, roles)", request.getRoles());
//            lqw.apply(StrUtil.format(" find_in_set('{}', roles)", request.getRoles()));
        }
        List<SystemAdmin> systemAdmins = dao.selectList(lqw);
        if (CollUtil.isEmpty(systemAdmins)) {
            return CollUtil.newArrayList();
        }
        List<SystemAdminResponse> adminResponseList = new ArrayList<>();
        List<SystemRole> roleList = systemRoleService.getListByMerId(currentAdmin.getMerId());
        for (SystemAdmin admin : systemAdmins) {
            SystemAdminResponse sar = new SystemAdminResponse();
            BeanUtils.copyProperties(admin, sar);
            sar.setLastTime(admin.getUpdateTime());
            List<Integer> roleIds = CrmebUtil.stringToArrayInt(admin.getRoles());
            List<String> roleNames = new ArrayList<>();
            for (Integer roleId : roleIds) {
                if (1 == roleId) {
                    roleNames.add("超级管理员");
                    continue;
                }
                if (2 == roleId) {
                    roleNames.add("商户超管");
                    continue;
                }
                for (SystemRole role : roleList) {
                    if (role.getId().equals(roleId)) {
                        roleNames.add(role.getRoleName());
                    }
                }
            }
            sar.setRoleNames(StringUtils.join(roleNames, ","));

            if (crmebConfig.getPhoneMaskSwitch() && StrUtil.isNotBlank(sar.getPhone())) {
                sar.setPhone(CrmebUtil.maskMobile(sar.getPhone()));
            }
            adminResponseList.add(sar);
        }
        return adminResponseList;
    }

    /**
     * 是否存在角色
     *
     * @param roleId 角色id
     * @return Boolean
     */
    @Override
    public Boolean isExistRole(Integer roleId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId);
        lqw.apply(StrUtil.format(" find_in_set('{}', roles)", roleId));
        lqw.last(" limit 1");
        SystemAdmin systemAdmin = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(systemAdmin);
    }

    /**
     * 新增管理员
     * @param systemAdminAddRequest 新增参数
     * @return Boolean
     */
    @Override
    public Boolean saveAdmin(SystemAdminAddRequest systemAdminAddRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        // 管理员名称唯一校验
        if (checkAccount(systemAdminAddRequest.getAccount())) {
            throw new CrmebException(AdminResultCode.ADMIN_EXIST);
        }

        SystemAdmin systemAdmin = new SystemAdmin();
        BeanUtils.copyProperties(systemAdminAddRequest, systemAdmin);

        String pwd = CrmebUtil.encryptPassword(systemAdmin.getPwd(), systemAdmin.getAccount());
        systemAdmin.setPwd(pwd);
        systemAdmin.setMerId(currentUser.getMerId());
        systemAdmin.setType(systemRoleService.getRoleTypeByCurrentAdmin());

        Boolean result = save(systemAdmin);

        if(result){
            //判断type=4
            if (systemAdmin.getType() == 4){
                Integer userId = systemAdmin.getId();
                Integer merId = systemAdmin.getMerId();

                //获取主账号的定位信息
                UserLocation userLocation = getUserLocation(merId);
                if (userLocation != null) {
                    //异步生成每日任务和专业榜单
                    CompletableFuture.runAsync(() -> {
                        try {
                            // insertUserLocation执行完毕后再执行createTopic，保证顺序
                            //生成子账号的定位信息，不用调用api，直接复制主账号下的
                            insertSubUserLocation(userLocation.getId(), userId);

                            Map<String, Object> agentUserInfo = getAgentUserInfo(userLocation);
                            //创建子账号的专业热榜
                            createTopic(userId, merId, agentUserInfo);
                        } catch (Exception e) {
                            log.error("异步插入用户位置或创建话题失败", e);
                        }
                    });

                    //异步生成周任务
                    CompletableFuture.runAsync(() -> {
                        try {
                            // 生成周任务
                            insertWeekTask(userLocation.getLocationResult(), userId, merId);
                        } catch (Exception e) {
                            log.error("异步插入周任务失败", e);
                        }
                    });

                }
            }
        }

        return result;
    }

    /**
     * 管理员名称唯一校验
     * @param account 管理员账号
     * @return Boolean
     */
    @Override
    public Boolean checkAccount(String account) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getAccount, account);
        lqw.eq(SystemAdmin::getIsDel, false);
        return dao.selectCount(lqw) > 0;
    }

    /**
     * 更新管理员
     */
    @Override
    public Boolean updateAdmin(SystemAdminUpdateRequest systemAdminRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        SystemAdmin adminDetail = getDetail(systemAdminRequest.getId());
        // 超级管理员不允许编辑
        if (adminDetail.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || adminDetail.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(adminDetail.getMerId())) {
            throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        verifyAccount(systemAdminRequest.getId(), systemAdminRequest.getAccount());
        SystemAdmin systemAdmin = new SystemAdmin();
        systemAdmin.setId(systemAdminRequest.getId());
        systemAdmin.setAccount(systemAdminRequest.getAccount());
        systemAdmin.setRealName(systemAdminRequest.getRealName());
        systemAdmin.setRoles(systemAdminRequest.getRoles());
        systemAdmin.setStatus(systemAdminRequest.getStatus());
        if (StrUtil.isNotBlank(systemAdminRequest.getPhone())) {
            systemAdmin.setPhone(systemAdminRequest.getPhone());
        }
        systemAdmin.setMerId(currentUser.getMerId());
        return updateById(systemAdmin);
    }

    /**
     * 删除管理员
     * @param id 管理员id
     * @return 删除结果
     */
    @Override
    public Boolean removeAdmin(Integer id) {
        SystemAdmin perDelAdmin = getDetail(id);
        if (perDelAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || perDelAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许删除");
        }
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        if (!admin.getMerId().equals(perDelAdmin.getMerId())) {
            throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        return removeById(id);
    }

    /**
     * 修改后台管理员状态
     * @param id 管理员id
     * @param status 状态
     * @return Boolean
     */
    @Override
    public Boolean updateStatus(Integer id, Boolean status) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        // 超级管理员不允许编辑
        SystemAdmin systemAdmin = getDetail(id);
        if (systemAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || systemAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(systemAdmin.getMerId())) {
            throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (systemAdmin.getStatus().equals(status)) {
            return true;
        }
        systemAdmin.setStatus(status);
        return updateById(systemAdmin);
    }

    /**
     * 管理员详情
     * @param id 管理员id
     * @return SystemAdmin
     */
    @Override
    public SystemAdmin getDetail(Integer id) {
        SystemAdmin systemAdmin = getById(id);
        if (ObjectUtil.isNull(systemAdmin) || systemAdmin.getIsDel()) {
            throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        if (admin.getMerId() > 0) {
            if (!admin.getMerId().equals(systemAdmin.getMerId())) {
                throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
            }
        }
        return systemAdmin;
    }

    /**
     * 获取管理员名称map
     * @param idList id列表
     * @return Map
     */
    @Override
    public Map<Integer, String> getNameMapByIdList(List<Integer> idList) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId, SystemAdmin::getRealName);
        lqw.in(SystemAdmin::getId, idList);
        List<SystemAdmin> adminList = dao.selectList(lqw);
        Map<Integer, String> map = CollUtil.newHashMap();
        adminList.forEach(admin -> {
            map.put(admin.getId(), admin.getRealName());
        });
        return map;
    }

    /**
     * 修改后台管理员手机号
     */
    @Override
    public Boolean updatePassword(SystemAdminUpdatePwdRequest request) {
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "两次密码输入不一致");
        }
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        SystemAdmin adminDetail = getDetail(request.getId());
        // 超级管理员不允许编辑
        if (adminDetail.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || adminDetail.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(adminDetail.getMerId())) {
            throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        SystemAdmin newAdmin = new SystemAdmin();
        newAdmin.setId(request.getId());
        newAdmin.setPwd(CrmebUtil.encryptPassword(request.getPassword(), adminDetail.getAccount()));
        return updateById(newAdmin);
    }

    /**
     * 商户后台管理员短信开关
     * @param adminId 商户管理员ID
     */
    @Override
    public Boolean updateReceiveSms(Integer adminId) {
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
//        if (admin.getMerId().equals(0)) {
//            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "平台管理员无接口短信开关");
//        }
        SystemAdmin systemAdmin = getById(adminId);
        if (!admin.getMerId().equals(systemAdmin.getMerId())) {
            throw new CrmebException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (!systemAdmin.getIsSms() && StrUtil.isBlank(systemAdmin.getPhone())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "请先为管理员设置手机号");
        }
        if (!ReUtil.isMatch(RegularConstants.PHONE_TWO, systemAdmin.getPhone())) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "请先为管理员设置手机号");
        }
        systemAdmin.setIsSms(!systemAdmin.getIsSms());
        return updateById(systemAdmin);
    }

    /**
     * 获取接收短信管理员列表
     *
     * @param merId 商户ID
     */
    @Override
    public List<SystemAdmin> findReceiveSmsAdminListByMerId(Integer merId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId, SystemAdmin::getPhone, SystemAdmin::getRealName);
        lqw.eq(SystemAdmin::getMerId, merId);
        lqw.eq(SystemAdmin::getIsSms, 1);
        lqw.eq(SystemAdmin::getStatus, 1);
        lqw.eq(SystemAdmin::getIsDel, 0);
        return dao.selectList(lqw);
    }

    /**
     * 越权登录获取商户超管账户
     * @param merId 商户ID
     */
    @Override
    public SystemAdmin getSuperAdminByPlat(Integer merId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getMerId, merId);
        lqw.eq(SystemAdmin::getType, RoleEnum.SUPER_MERCHANT.getValue());
        lqw.eq(SystemAdmin::getIsDel, false);
        lqw.last(" limit 1");
        return dao.selectOne(lqw);
    }

    /**
     * 校验账号唯一性（管理员更新时）
     * @param id 管理员id
     * @param account 管理员账号
     */
    private void verifyAccount(Integer id, String account) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.ne(SystemAdmin::getId, id);
        lqw.eq(SystemAdmin::getAccount, account);
        SystemAdmin systemAdmin = dao.selectOne(lqw);
        if (ObjectUtil.isNotNull(systemAdmin)) {
            throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "账号已存在");
        }
    }

    /**
     * 登录之前查询权限带上超管标识
     *
     * @param type 用户类型
     */
    private List<Integer> addSuperRoleType(Integer type) {
        List<Integer> types = new ArrayList<>();
        if (type.equals(RoleEnum.PLATFORM_ADMIN.getValue())) {
            types.add(RoleEnum.SUPER_ADMIN.getValue());
            types.add(RoleEnum.PLATFORM_ADMIN.getValue());
        }
        if (type.equals(RoleEnum.MERCHANT_ADMIN.getValue())) {
            types.add(RoleEnum.SUPER_MERCHANT.getValue());
            types.add(RoleEnum.MERCHANT_ADMIN.getValue());
        }
        return types;
    }

    /**
     * 主账号的userLocation信息
     * @param merId
     * @return
     */
    private UserLocation getUserLocation(Integer merId) {
        //查找systemAdmin 中type=2的用户
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getMerId, merId);
        lqw.eq(SystemAdmin::getType, 2);
        SystemAdmin systemAdmin = dao.selectOne(lqw);

        UserLocation userLocation = userLocationService.lambdaQuery()
                .eq(UserLocation::getIsDel, 0)
                .eq(UserLocation::getUserId, systemAdmin.getId())
                .one();

        return userLocation;
    }

    /**
     * 子账号直接使用主账号的定位信息
     * @param id 主账号的userLocation的id
     * @param userId 子账号的id
     * @return
     */
    public UserLocation insertSubUserLocation(Integer id, Integer userId){
        //获取主账号下的定位信息
        UserLocation userLocation = userLocationService.getById(id);

        UserLocation subUserLocation = new UserLocation();
        subUserLocation.setUserId(userId);
        subUserLocation.setMerId(userLocation.getMerId());

        //一句话描述
        subUserLocation.setLocationDesc(userLocation.getLocationDesc());

        //markdown返回的结果
        subUserLocation.setLocationResult(userLocation.getLocationResult());

        subUserLocation.setIndustry(userLocation.getIndustry());
        subUserLocation.setRegion(userLocation.getRegion());
        subUserLocation.setSubIndustry(userLocation.getSubIndustry());
        subUserLocation.setTargetAudience(userLocation.getTargetAudience());
        subUserLocation.setMarketingNeeds(userLocation.getMarketingNeeds());

        boolean save = userLocationService.save(subUserLocation);
        return subUserLocation;
    }

    /**
     * 创建话题并保存到数据库
     * @param userId 用户ID
     * @param merId 商户ID
     * @return 插入的记录ID列表
     */
    public List<Integer> createTopic(Integer userId, Integer merId, Map<String, Object> agentUserInfo) {
        List<String> categoryList = Arrays.asList(
                "情感共鸣类", "观点输出类", "吐槽互动类", "知识科普类",
                "故事分享类", "回忆怀旧类", "群体认同类", "⼼声代⾔类"
        );

        List<Integer> insertedIds = new ArrayList<>();

        try {
            // 1. 从categoryList中随机选择三个
            List<String> randomCategories = new ArrayList<>(categoryList);
            Collections.shuffle(randomCategories);
            List<String> selectedCategories = randomCategories.subList(0, 2);

            // 2. 添加"轻度营销类"
            selectedCategories.add("轻度营销类");

            log.info("选择的创作类型：{}", selectedCategories);

            // 3. 保存到用户选题类型表或者更新表
            UserSpecialTopicCategory userCategoryById = userSpecialTopicCategoryService.getByUserId(userId);
            Integer categoryId = 0;
            if (userCategoryById != null) {
                userCategoryById.setCategorys(selectedCategories);
                userSpecialTopicCategoryService.updateById(userCategoryById);
                categoryId = userCategoryById.getId();
                log.info("更新用户选题类型成功，ID：{}，创作类型:{}", userCategoryById.getId(), selectedCategories);
            }else{
                UserSpecialTopicCategory userCategory = new UserSpecialTopicCategory();
                userCategory.setCategorys(selectedCategories);
                userCategory.setUserId(userId);
                userCategory.setMerId(merId);
                userSpecialTopicCategoryService.save(userCategory);
                categoryId = userCategory.getId();
                log.info("保存用户选题类型成功，ID：{}，创作类型:{}", userCategory.getId(), selectedCategories);
            }

            // 4. 循环每个创作类型，调用createTopicApi
            for (String category : selectedCategories) {

                //循环调用创作话题的api，生成数据
                Map<String, Object> topicResult = new HashMap<>();
                if (category.equals("轻度营销类")){
                    topicResult = createTopicApi(category,1, agentUserInfo);
                }else{
                    topicResult = createTopicApi(category,0, agentUserInfo);
                }

                log.info("专业榜单返回的数据为：{}", topicResult);

                if (topicResult != null && !topicResult.isEmpty()) {
                    String categoryName = (String) topicResult.get("category");
                    String targetAnalysis = (String) topicResult.get("target_analysis");
                    List<Map<String, Object>> topics = (List<Map<String, Object>>) topicResult.get("topics");

                    // 5. 保存话题到数据库
                    if (topics != null) {
                        for (Map<String, Object> topic : topics) {
                            SpecialHotTopic specialHotTopic = new SpecialHotTopic();
                            specialHotTopic.setCategory(categoryName);
                            specialHotTopic.setTargetAnalysis(targetAnalysis);
                            specialHotTopic.setTitle((String) topic.get("title"));
                            specialHotTopic.setDescription((String) topic.get("description"));
                            specialHotTopic.setPurpose((String) topic.get("purpose"));
                            specialHotTopic.setUserId(userId);
                            specialHotTopic.setMerId(merId);

                            specialHotTopicService.save(specialHotTopic);
                            insertedIds.add(specialHotTopic.getId());

                            log.info("保存话题成功，ID：{}，标题：{}", specialHotTopic.getId(), specialHotTopic.getTitle());
                        }
                    }
                }
            }

            log.info("成功创建{}个话题", insertedIds.size());

        } catch (Exception e) {
            log.error("创建话题过程中发生错误", e);
        }

        return insertedIds;
    }

    /**
     * 创建热点榜单API
     * 发送消息到热点榜单创建的AI代理服务
     *
     * @param message 用户消息
     * @return 代理响应结果
     */
    public Map<String, Object> createTopicApi(String message, Integer isMarketing, Map<String, Object> agentUserInfo) {
        // JSON字符串
        String jsonString = "{\n" +
                "  \"category\": \"String\",\n" +
                "  \"target_analysis\": \"String\",\n" +
                "  \"topics\": [\n" +
                "    {\n" +
                "      \"title\": \"String\",\n" +
                "      \"description\": \"String\",\n" +
                "      \"purpose\": \"String\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"strategy_notes\": \"String\"\n" +
                "}";

        // 转换为Map
        JSONObject jsonObject = JSON.parseObject(jsonString);
        Map<String, Object> outputFormatMap = (Map<String, Object>) JSON.toJSON(jsonObject);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("outputFormat", outputFormatMap);

        List<String> instructions = new ArrayList<>();

        String agentId = "";
        if(isMarketing == 1){
            agentId = "622d8641-168b-49f2-8be4-3fa8e21ad99f";
            //营销类的
            instructions.add("输出结构字段含义说明：category: 内容分类类型，固定为\"轻度营销类\" target_analysis: 目标群体深度分析，包括年龄段、职业特征、生活状态、心理特征、核心痛点等详细描述 topics: 选题列表数组，每个选题包含以下字段 topics[].title: 选题标题，需要具有吸引力和共鸣感，可包含轻度营销元素 topics[].description: 选题内容描述，简要说明选题的核心内容和表达方式 topics[].purpose: 选题目的，说明该选题希望达到的共鸣效果或营销转化价值 strategy_notes: 策略备注，说明整体选题策略、目标用户痛点、营销转化设计思路等");
        }else{
            //非营销类的
            agentId = "cdfbfb59-c721-4162-b8d8-0e745ad09b4d";
            instructions.add("输出结构字段含义说明：category: 内容分类类型，如\"情感共鸣类\"、\"观点输出类\"、\"吐槽互动类\"等 target_analysis: 目标群体深度分析，包括年龄段、职业特征、生活状态、心理特征、核心痛点等详细描述 topics: 选题列表数组，每个选题包含以下字段 topics[].title: 选题标题，需要具有吸引力和共鸣感，避免营销色彩 topics[].description: 选题内容描述，简要说明选题的核心内容和表达方式 topics[].purpose: 选题目的，说明该选题希望达到的共鸣效果或情感价值 strategy_notes: 策略备注，说明整体选题策略、目标用户痛点、共鸣设计思路等");
        }
        Map<String, Object> map = agenticAgentApi(message, hashMap, instructions,agentId, agentUserInfo);
        log.info("返回的结构是：{}", map);
        if (map != null && map.get("msg") == null) {
            return (Map<String, Object>) map.get("result");
        }

        return map;
    }

    /**
     * 调用agent返回标题
     * @param content 内容
     * @return
     */
    public Map<String , Object> agenticAgentApi(String content, Map<String, Object> outputFormat, List<String> instructions, String agent_id, Map<String, Object> agentUserInfo) {
        String url = agentBaseUrl + "/api/v1/agents/agentic";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        //拼接结构化的参数
        Map<String, Object> body = new HashMap<>();
        body.put("instructions", instructions);
        body.put("message", content);

        if(agent_id == null || agent_id.isEmpty()){
            // 使用模型 结构化输出
            body.put("model_id", "8b407a9d-0c76-49f1-8dcd-840b8e29f886");
        }else{
            // 使用代理 结构化输出
            body.put("agent_id", agent_id);
        }

        //传用户信息
        if (agentUserInfo != null) {
            //用户信息可以传空
            body.put("user_info", agentUserInfo);
        }

        Map<String, Double> option = new HashMap<>();
        option.put("temperature", 0.7);
        body.put("options", option);
        body.put("output_format", outputFormat.get("outputFormat"));

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        //定义异常返回的内容
        Map<String, Object> map = new HashMap<>();

        try{
            // 仅在本方法内设置 RestTemplate 超时时间为 200000ms
            ClientHttpRequestFactory originalFactory = restTemplate.getRequestFactory();
            SimpleClientHttpRequestFactory tempFactory = new SimpleClientHttpRequestFactory();
            tempFactory.setConnectTimeout(200000);
            tempFactory.setReadTimeout(200000);
            restTemplate.setRequestFactory(tempFactory);

            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);

            // 恢复原有工厂
            restTemplate.setRequestFactory(originalFactory);
            Map<String, Object> respBody = response.getBody();
            if (respBody == null) {
                throw new CrmebException("agent接口响应为空");
            }
            Object codeObj = respBody.get("code");
            if (codeObj != null && Integer.valueOf(200).equals(codeObj)) {
                Map<String, Object> data = (Map<String, Object>) respBody.get("data");
                if (data != null) {
//                String messageStr = data.get("message").toString();
//                JSONObject messageJson = JSONObject.parseObject(messageStr);
//                Map<String , Object> json = (Map<String , Object>)JSONObject.toJSON(messageJson);
                    return data;
//                return data.get("message");
                } else {
                    map.put("msg", "agent接口返回数据格式异常");
                    log.error("agent接口返回格式异常，返回内容为：{} ",respBody);
                    return map;
                }
            } else {
                String msg = respBody.get("message").toString();
                map.put("msg", msg);
                log.error("agent接口返回错误信息：{} ",msg);
                return map;
            }
        }catch (Exception e){
            String msg = "agent接口返回异常:" + e.getMessage().toString();
            map.put("msg", msg);
            log.error("agent接口返回格式异常，返回内容为：{} ",msg);
            return map;
        }
    }

    /**
     * 请求agent将返回的数据写入到周任务表中
     * @param message 用户消息
     * @param userId 用户ID
     * @param merId 商户ID
     * @return 插入的记录ID列表
     */
    public List<Integer> insertWeekTask(String message, Integer userId, Integer merId){
        // 每次先把之前生成的本周任务标记为删除状态
        Map<String, String> weekDates = getCurrentWeekDates();
        String mondayDate = weekDates.get("monday");
        String sundayDate = weekDates.get("sunday");

        log.info("准备删除本周任务，日期范围：{} 到 {}", mondayDate, sundayDate);

        // 删除逻辑：根据本周日期范围和userId，将符合条件的记录标记为is_del=1
        boolean deleteResult = weekTaskService.lambdaUpdate()
                .eq(WeekTask::getUserId, userId)
                .eq(WeekTask::getIsDel, 0)
                .ge(WeekTask::getDay, java.sql.Date.valueOf(mondayDate))
                .le(WeekTask::getDay, Date.valueOf(sundayDate))
                .set(WeekTask::getIsDel, 1)
                .update();

        log.info("删除本周任务记录结果：{}", deleteResult);

        Map<String, Object> map = weekTaskAgentApi(message);
        List<Integer> insertedIds = new ArrayList<>();

        // 获取今天是周几和日期
        LocalDate today = LocalDate.now();
        String todayOfWeek = getDayOfWeekChinese(today.getDayOfWeek().getValue());
        String todayStr = today.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        log.info("今天是：{}，日期：{}", todayOfWeek, todayStr);

        // 获取第一周和第二周的数据
        List<Map<String, Object>> firstWeek = (List<Map<String, Object>>)map.get("first_week");
        List<Map<String, Object>> secondWeek = (List<Map<String, Object>>)map.get("second_week");

        // 计算本周的起始日期（周一）
        LocalDate weekStart = today.minusDays(today.getDayOfWeek().getValue() - 1);

        // 处理第一周数据
        if (firstWeek != null) {
            for (int i = 0; i < firstWeek.size(); i++) {
                Map<String, Object> taskData = firstWeek.get(i);
                WeekTask weekTask = createWeekTask(taskData, userId, merId, weekStart.plusDays(i), "first");
                weekTaskService.save(weekTask);
                insertedIds.add(weekTask.getId());
            }
        }

        // 处理第二周数据---先注释
//        if (secondWeek != null) {
//            LocalDate nextWeekStart = weekStart.plusDays(7);
//            for (int i = 0; i < secondWeek.size(); i++) {
//                Map<String, Object> taskData = secondWeek.get(i);
//                WeekTask weekTask = createWeekTask(taskData, userId, merId, nextWeekStart.plusDays(i), "second");
//                weekTaskService.save(weekTask);
//                insertedIds.add(weekTask.getId());
//            }
//        }

        log.info("成功插入{}条周任务记录", insertedIds.size());

        return insertedIds;
    }

    /**
     * 创建WeekTask对象
     */
    private WeekTask createWeekTask(Map<String, Object> taskData, Integer userId, Integer merId,
                                    LocalDate date, String week) {
        WeekTask weekTask = new WeekTask();
        weekTask.setUserId(userId);
        weekTask.setMerId(merId);
        weekTask.setWeek(week);
        weekTask.setDay(Date.valueOf(date));
//        weekTask.setDayOfWeek(date.getDayOfWeek().getValue());
        weekTask.setDayOfWeek((String) taskData.get("date"));
        weekTask.setIsDel(0);

        // 设置任务相关字段
        weekTask.setContentType((String) taskData.get("content_type"));
        weekTask.setTaskDescription((String) taskData.get("task_description"));
        weekTask.setRecommendedTopic((String) taskData.get("recommended_topic"));
        weekTask.setTargetAudience((String) taskData.get("target_audience"));
        weekTask.setTaskPurpose((String) taskData.get("task_purpose"));
        weekTask.setStrategyFocus((String) taskData.get("strategy_focus"));
        weekTask.setContentAttribute((String) taskData.get("content_attribute"));

        // 设置优先级和难度
//        String priorityStr = (String) taskData.get("priority");
        weekTask.setPriority((String) taskData.get("priority"));

//        String difficultyStr = (String) taskData.get("creation_difficulty");
        weekTask.setCreationDifficulty((String) taskData.get("creation_difficulty"));

        return weekTask;
    }

    /**
     * 获取中文星期几
     */
    private String getDayOfWeekChinese(int dayOfWeek) {
        String[] weekDays = {"", "周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        return weekDays[dayOfWeek];
    }

    /**
     * 用户位置代理API
     * 发送消息到位置相关的AI代理服务
     *
     * @param message 用户消息
     * @return 代理响应结果
     */
    public Map<String , Object> weekTaskAgentApi(String message) {
        // JSON字符串
        String jsonString = "{\n" +
                "  \"first_week\": [\n" +
                "    {\n" +
                "      \"date\": \"String\",\n" +
                "      \"content_type\": \"String\",\n" +
                "      \"task_description\": \"String\",\n" +
                "      \"recommended_topic\": \"String\",\n" +
                "      \"target_audience\": \"String\",\n" +
                "      \"task_purpose\": \"String\",\n" +
                "      \"priority\": \"String\",\n" +
                "      \"creation_difficulty\": \"String\",\n" +
                "      \"content_attribute\": \"String\",\n" +
                "      \"strategy_focus\": \"String\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"date\": \"String\",\n" +
                "      \"content_type\": \"String\",\n" +
                "      \"task_description\": \"String\",\n" +
                "      \"recommended_topic\": \"String\",\n" +
                "      \"target_audience\": \"String\",\n" +
                "      \"task_purpose\": \"String\",\n" +
                "      \"priority\": \"String\",\n" +
                "      \"creation_difficulty\": \"String\",\n" +
                "      \"content_attribute\": \"String\",\n" +
                "      \"strategy_focus\": \"String\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        // 转换为Map
        JSONObject jsonObject = JSON.parseObject(jsonString);
        Map<String, Object> outputFormatMap = (Map<String, Object>) JSON.toJSON(jsonObject);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("outputFormat", outputFormatMap);

        List<String> instructions = new ArrayList<>();
        instructions.add("输出结构的字段含义： date: 具体创作日期，周一至周日标注 content_type: 具体创作内容，6字以内，如\"情感共鸣类\" task_description: 任务描述，具体创作内容，20字以内，简洁明确 recommended_topic: 推荐选题，具体选题建议 target_audience: 目标角色，内容针对的角色，具体到人群 task_purpose: 任务目的，创作意图和目标，明确创作目的 priority: 优先级，重要程度，高｜中 creation_difficulty: 创作难度，执行复杂度，简单/中等/复杂 content_attribute: 内容属性，营销属性分类，纯共鸣/软营销/硬营销 strategy_focus: 创作策略重点，从群体洞察、群体共鸣、价值提供等方向着手详细说明创作策略（35字以内）");

        Map<String, Object> map = agenticAgentApi(message, hashMap, instructions, null, null);
        log.info("返回的结构是：{}", map);
        if (map != null && map.get("msg") == null) {
            return (Map<String , Object>)map.get("result");
        }

        return map;

    }

    /**
     * 根据当前日期返回这周周一的日期和周日的日期
     * @return Map包含monday和sunday两个key，值为yyyy-MM-dd格式的日期字符串
     */
    public Map<String, String> getCurrentWeekDates() {
        LocalDate today = LocalDate.now();

        // 计算本周周一（当前日期减去当前是周几的天数，再加1天）
        LocalDate monday = today.minusDays(today.getDayOfWeek().getValue() - 1);

        // 计算本周周日（周一加6天）
        LocalDate sunday = monday.plusDays(6);

        Map<String, String> weekDates = new HashMap<>();
        weekDates.put("monday", monday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        weekDates.put("sunday", sunday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        log.info("当前周日期范围：周一 {} 到周日 {}", weekDates.get("monday"), weekDates.get("sunday"));

        return weekDates;
    }

    /**
     * 获取代理用户信息
     * 根据用户位置信息构建代理服务所需的用户信息参数
     *
     * @param userLocation 用户位置信息
     * @return 代理服务用户信息参数
     */
    public Map<String, Object> getAgentUserInfo(UserLocation userLocation) {
        log.info("开始构建代理用户信息，用户ID: {}", userLocation.getUserId());

        // 2. 拼接user_info参数
        Map<String, Object> userInfoJson = new HashMap<>();
        Map<String, Object> userInfoRequestJson = new HashMap<>();
        Map<String, Object> userInfoProfileJson = new HashMap<>();

        userInfoProfileJson.put("industry", userLocation.getIndustry());
        userInfoProfileJson.put("sub_industry", userLocation.getSubIndustry());
        userInfoProfileJson.put("region", userLocation.getRegion());

        userInfoJson.put("profile", userInfoProfileJson);
        userInfoJson.put("marketing_needs", userLocation.getMarketingNeeds());
        userInfoJson.put("target_audience", userLocation.getTargetAudience());

        userInfoRequestJson.put("user", userInfoJson);

        log.info("代理用户信息构建完成: {}", userInfoRequestJson);
        return userInfoRequestJson;
    }

}

